<template>
  <div :class="$style.signInOrOut">
    <Icon :allow="true" :src="src" :srcset="srcset" :text="text" @on-click="iconClickHandle" />
    <el-dialog
      :visible.sync="visible"
      append-to-body
      :close-on-click-modal="false"
      title="选择签出原因"
    >
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item prop="reason" label="签出原因">
          <el-select
            v-model="formData.reason"
            placeholder="请选择签出原因"
            clearable
            filterable
            style="width:100%"
          >
            <el-option v-for="(r,i) in signOutReasonList" :key="i" :value="r.dictCode" :label="r.dictName" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div :class="$style.btn">
            <Button @click="visible=false">取消</Button>
            <Button type="primary" :loading="loading" @click="confirmHandle">确定</Button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import Icon from './Icon'
import beforeSign from './js/beforeSign.js'
import afterSign from './js/afterSign.js'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { ccDict } from '@/api/dataDict'
export default {
  name: 'SignInOrOut',
  components: {
    Icon
  },

  data() {
    return {
      loading: false,
      visible: false,
      signOutReasonList: [], // 签出原因
      formData: {
        reason: ''
      },
      formRules: {
        reason: [
          { required: true, message: '请选择签出原因', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['callInfo', 'agentState', 'interval', 'skillList', 'queueSize', 'agentid', 'phonenum', 'agentInfo']),
    src() {
      return this.allow ? afterSign.signing : beforeSign.signing
    },
    srcset() {
      return this.allow ? afterSign.signing2x : beforeSign.signing2x
    },
    text() {
      return this.allow ? '已签入' : '未签入'
    },
    allow() {
      return this.agentState.sign
    }
  },
  watch: {
    agentid() {
      this.$cps.setParam(this.interval, this.agentid, '', this.phonenum)
    },
    phonenum() {
      this.$cps.setParam(this.interval, this.agentid, '', this.phonenum)
    }
  },
  created() {
    // FIXME:注意修改轮询时间
    this.$cps.setParam(this.interval, this.agentid, '', this.phonenum)
    this.$cps.bus.$on('OnSignInSuccess', this.signInSuccess)
    this.$cps.bus.$on('OnSignOutSuccess', this.signOutSuccess)
    this.ccDict()
  },
  beforeDestroy() {
    this.$cps.bus.$off('OnSignInSuccess', this.signInSuccess)
    this.$cps.bus.$off('OnSignOutSuccess', this.signOutSuccess)
  },
  methods: {
    ...mapMutations(['SET_AGENT_INFO', 'SET_AGENT_STATE']),
    ...mapActions(['queryAgentInfoByWorkNo']),
    // 签入成功
    signInSuccess() {
      this.$notifySuccess('签入成功！')
    },
    // 签出成功
    signOutSuccess() {
      this.$notifySuccess('签出成功！')
    },
    // 话务条被单击
    iconClickHandle() {
      if (!this.phonenum) {
        this.$msgbox.alert('无分机号，请退出重新登录！', '提示')
        return
      }
      if (this.allow) {
        this.visible = true
      } else {
        // 签入操作
        this.signInHandle()
      }
    },
    // 签入操作
    signInHandle() {
      // 如果没有平台工号或分机号不能操作
      if (!this.agentid) {
        this.$notifyError('您没有平台工号！')
        return
      }
      if (!this.phonenum) {
        this.$notifyError('请输入分机号！')
        return
      }
      // TODO:开发时使用强制签入
      // let apiName = 'signIn'
      // this.$dev ? apiName = 'forceSignIn' : apiName = 'signIn'
      const apiName = 'forceSignIn'
      this.$cps[apiName](true, true).then(() => { // 不能填自动应答
        this.$callOperatorLogSuccess(1) // 签入成功
        this.queryAgentInfoByWorkNo(this.agentid)
      }).catch(() => {
        this.$callOperatorLogFail(1) // 签入失败
      })
    },
    // 弹窗后确认
    confirmHandle() {
      this.loading = true
      this.$refs.form
        .validate()
        .then(() => {
          let reasonText = ''
          for (const d of this.signOutReasonList) {
            if (this.formData.reason === d.dictCode) {
              reasonText = d.dictName
              break
            }
          }
          return this.$cps.forcelogoutwithreason(this.formData.reason).then(() => {
            this.resetState()
            this.visible = false
            this.$callOperatorLogSuccess(2, reasonText) // 签出成功
            this.$cps.bus.$emit('OnSignOutSuccess')
          }).catch(() => {
            this.$callOperatorLogFail(2, reasonText) // 签出失败
            this.$notifyError('签出失败！')
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 签出成功后重置所有状态
    resetState() {
      const keys = ['sign', 'free', 'talk', 'work', 'answer', 'hold', 'mute', 'mpty']
      for (const key of keys) {
        this.SET_AGENT_STATE({ key, value: false })
      }
    },
    // 获取签出的数据字典
    ccDict() {
      ccDict('LOGOUT_REASON').then(res => {
        this.signOutReasonList = res.data
      })
    }
  }
}
</script>
<style lang="scss" module>
@import "@/styles/mixin.scss";
.signInOrOut {
}
.btn{
  @include flex($justify: flex-end);
}
</style>
